package org.netspeak.android.app;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.List;

import org.netspeak.android.utils.ParcelablePhrase;
import org.netspeak.application.generated.NetspeakMessages.Phrase;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

/**
 * {@link ArrayAdapter} extension for setting {@link Phrase} results as data for 
 * a ListView.
 *
 * @author Teresa Holfeld, teresa.holfeld@gmail.com
 */
public class ResultListArrayAdapter extends ArrayAdapter<ParcelablePhrase> {
    
    /** Formats float as needed for display in ListView. */
    private static final NumberFormat FORMAT = new DecimalFormat("##0.0'%'");
    
    private Context mContext;
    private int mListViewResourceId;
    private List<ParcelablePhrase> mPhrases;
    private long mTotalFrequency;
    
    /** Cache for better performance. */
    private static class ViewHolder {
        public TextView mTextView;
        public TextView mFrequencyView;
    }

    public ResultListArrayAdapter(Context context, int listViewResourceId, 
            List<ParcelablePhrase> phrases, long totalFrequency) {
        super(context, listViewResourceId, phrases);
        mContext = context;
        mListViewResourceId = listViewResourceId;
        mPhrases = phrases;
        mTotalFrequency = totalFrequency;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View rowView = convertView;
        if (rowView == null) {
            LayoutInflater inflater = (LayoutInflater) mContext
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            rowView = inflater.inflate(mListViewResourceId, parent, false);
            ViewHolder viewHolder = new ViewHolder();
            viewHolder.mTextView = (TextView) rowView
                    .findViewById(R.id.resultText);
            viewHolder.mFrequencyView = (TextView) rowView
                    .findViewById(R.id.resultFrequency);
            rowView.setTag(viewHolder);
        }
        
        ViewHolder viewHolder = (ViewHolder) rowView.getTag();
        ParcelablePhrase phrase = mPhrases.get(position);
        viewHolder.mTextView.setText(phrase.getText());
        double percent = ((double) phrase.getFrequency() 
                / (double) mTotalFrequency) * 100;
        viewHolder.mFrequencyView.setText(FORMAT.format(percent));
        return rowView;
    }
}
